package com.hmall.item.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.FiltersDto;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Filters;
import com.hmall.common.pojo.Item;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 修改商品状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatusById(Long id, Integer status) {
        this.lambdaUpdate().set(Item::getStatus, status)
                .set(Item::getUpdateTime, LocalDateTime.now())
                .eq(Item::getId, id).update();
        rabbitTemplate.convertAndSend("statusUpdate.queue", "update");

    }

    /**
     * 查询商品分类和品牌
     *
     * @param filtersDto
     * @return
     */
    @Override
    public Filters getFilters(FiltersDto filtersDto) {
        List allCategory = itemMapper.selectAllCategory();
        List allBrand = itemMapper.selectAllBrand();
        return new Filters(allCategory, allBrand);
    }


    /**
     * 根据条件查询商品
     *
     * @param filtersDto
     * @return
     */
    @Override
    public PageDTO<Item> searchByCondition(FiltersDto filtersDto) {
//        String s = UserThreadLocal.get();
//        log.info("userId: {}", s);

        //如果是热点数据
        if (filtersDto.getKey() == "" && filtersDto.getPage() == 1
                && filtersDto.getSize() == 20 && "default".equals(filtersDto.getSortBy())
                && filtersDto.getCategory() == null && filtersDto.getBrand() == null
                && filtersDto.getMinPrice() == null && filtersDto.getMaxPrice() == null) {
            //先从redis中拿
            String hotItemsStr = redisTemplate.opsForValue().get("hotItems");
            if (hotItemsStr != null) {
                return JSONUtil.toBean(hotItemsStr, PageDTO.class);
            }
        }

        // 创建 LambdaQueryWrapper 对象
        LambdaQueryWrapper<Item> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.select(Item::getId, Item::getName, Item::getPrice, Item::getImage, Item::getCategory, Item::getBrand);
        queryWrapper.eq(Item::getStatus, 1);
        // 添加动态查询条件
        if (filtersDto.getKey() != null && !filtersDto.getKey().isEmpty()) {
            queryWrapper.like(Item::getName, filtersDto.getKey());
        }
        if (filtersDto.getCategory() != null && !filtersDto.getCategory().isEmpty()) {
            queryWrapper.eq(Item::getCategory, filtersDto.getCategory());
        }
        if (filtersDto.getBrand() != null && !filtersDto.getBrand().isEmpty()) {
            queryWrapper.eq(Item::getBrand, filtersDto.getBrand());
        }
        if (filtersDto.getMinPrice() != null) {
            queryWrapper.ge(Item::getPrice, filtersDto.getMinPrice());
        }
        if (filtersDto.getMaxPrice() != null) {
            queryWrapper.le(Item::getPrice, filtersDto.getMaxPrice());
        }

        // 设置排序规则
        if (filtersDto.getSortBy() != null && !filtersDto.getSortBy().isEmpty()) {
            boolean desc = filtersDto.getSortBy().equalsIgnoreCase("desc");
            switch (filtersDto.getSortBy().toLowerCase()) {
                case "price":
                    queryWrapper.orderBy(true, desc, Item::getPrice);
                    break;
                case "sold":
                    queryWrapper.orderBy(true, desc, Item::getSold);
                    break;
                default:
                    // 默认排序
                    queryWrapper.orderBy(true, false, Item::getSold);
                    break;
            }
        } else {
            // 默认排序
            queryWrapper.orderBy(true, false, Item::getSold);
        }

        Page<Item> itemPage = new Page<>(filtersDto.getPage(), filtersDto.getSize());
//        Page<Item> itemPage1 = itemMapper.selectPage(itemPage, queryWrapper);
        Page<Item> itemPage1 = this.page(itemPage, queryWrapper);
//        itemPage1.setTotal(Long.valueOf(itemPage1.getRecords().size()));
        return new PageDTO<>(itemPage1.getTotal(), itemPage1.getRecords());
    }

    /**
     * 扣减库存
     *
     * @param id
     * @param num
     */
    @Override
    public void updateStock(Long id, Integer num) {
        Item item = this.getById(id);
        this.lambdaUpdate()
                .set(num!= null , Item::getStock, item.getStock()-num)
                .set(Item::getUpdateTime, LocalDateTime.now())
                .ge(Item::getStock, num)
                .eq(Item::getId, id).update();
    }
    /**
     * 恢复库存
     *
     * @param id
     * @param num
     */
    @Override
    public void reStock(Long id, Integer num) {
        Item item = this.getById(id);
        this.lambdaUpdate()
                .set(num!= null , Item::getStock, item.getStock()+num)
                .set(Item::getUpdateTime, LocalDateTime.now())
                .ge(Item::getStock, num)
                .eq(Item::getId, id).update();
    }

    /**
     * 查找热门商品
     *
     * @return
     */
    @Override
    public List<Item> hotItems() {
        List<Item> list = this.lambdaQuery()
                .eq(Item::getStatus, 1)
                .orderByDesc(Item::getSold)
                //只要前20条
                .last("limit 20")
                .list();
        return list;

    }
}
